const WebSocket = require('ws');
const { verifyToken } = require('../auth/jwt');
const { wsRoutes } = require('../config/routes');

// WebSocket连接处理
function handleWebSocketConnection(wss) {
  wss.on('connection', (ws, req) => {
    console.log('WebSocket client connected');

    // 认证WebSocket连接 - 从查询参数获取token
    let token = null;
    const urlParts = req.url.split('?');
    if (urlParts.length > 1) {
      const urlParams = new URLSearchParams(urlParts[1]);
      token = urlParams.get('token');
    }

    if (!token) {
      ws.close(4001, 'Unauthorized: No token provided');
      return;
    }

    const user = verifyToken(token);

    if (!user) {
      ws.close(4001, 'Unauthorized: Invalid token');
      return;
    }

    // 提取路径以确定要代理到哪个服务
    const path = req.url;
    let targetWsUrl = null;

    for (const route of wsRoutes) {
      if (path.startsWith(route.path)) {
        targetWsUrl = `${route.target}${path.replace(route.path, '')}`;
        break;
      }
    }

    if (!targetWsUrl) {
      console.log('Invalid service path:', path);

      ws.close(4002, 'Invalid service path');
      return;
    }

    // 连接到目标WebSocket服务
    const targetWs = new WebSocket(targetWsUrl);

    // 添加连接超时处理
    const connectionTimeout = setTimeout(() => {
      ws.close(1006, 'Target service connection timeout');
    }, 5000);

    // 处理目标服务连接成功
    targetWs.on('open', () => {
      clearTimeout(connectionTimeout);
      console.log(`Connected to target service: ${targetWsUrl}`);

   

    });

    // 转发客户端消息到目标服务
    ws.on('message', (message) => {
      if (targetWs.readyState === WebSocket.OPEN) {
        targetWs.send(message);
      }
    });

    // 转发目标服务消息到客户端
    targetWs.on('message', (message) => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(message);
      }
    });

    // 处理客户端关闭
    ws.on('close', () => {
      console.log('WebSocket client disconnected');
      targetWs.close();
    });

    // 处理目标服务关闭
    targetWs.on('close', () => {
      ws.close(1001, 'Target service disconnected');
    });

    // 处理目标服务错误
    targetWs.on('error', (err) => {
      console.error('WebSocket target error:', err);
      ws.close(1011, 'Target service error');
    });
  });
}

module.exports = {
  handleWebSocketConnection
};